package com.mibus.mibusmobile;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;


import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class GpsService extends Service implements LocationListener{
    private Context mContext;

    private double latitud;
    private double longitud;
    private double velocidad;
    private String fechaPedirPosicion;
    private String fechaPosicionObtenida;
    private String id_recorrido_realizado;
    private String hash_session;
    private List<Integer> ids_paradas_cercanas = new ArrayList<Integer>();
    private Location loc;
    private RastreoActivity activity;
    private TextView tvProximaParada;
    private TextView tvProximaParada1;
    private TextView tvProximaParada2;
    private TextView tvProximaParadaReservas;
    private TextView tvPuestosDisponibles;
    private TextView tvOcupados;
    private ExecutorService threadPool;

    private long MIN_TIME = 1000; // 1 segundos
    LocationManager locManager;

    private SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private final String MOBILE_APP_URL = "http://mibus.eia.edu.co/Tablet/";
    private static ErrorLog log;

    public GpsService(Context context, long update_time, String hash_session, String id_recorrido_realizado) {
        super();
        this.activity = (RastreoActivity) context;
        this.mContext = context;
        this.MIN_TIME = update_time;
        this.hash_session = hash_session;
        this.id_recorrido_realizado = id_recorrido_realizado;
        threadPool = Executors.newSingleThreadExecutor();
        locManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
        fechaPedirPosicion = dateFormater.format(new Date());
       // locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, 0, this);
        tvProximaParada = (TextView) activity.findViewById(R.id.tvProximaParada);
        tvProximaParadaReservas = (TextView) activity.findViewById(R.id.tvProximaParadaReservas);

        tvProximaParada1 = (TextView) activity.findViewById(R.id.tvProximaParada1);
        tvProximaParada2 = (TextView) activity.findViewById(R.id.tvProximaParada2);
        tvPuestosDisponibles = (TextView) activity.findViewById(R.id.tvPuestosDisponibles);
        tvOcupados = (TextView) activity.findViewById(R.id.tvOcupados);

        log = new ErrorLog("RecorridoRealizadoGPS"+id_recorrido_realizado);
    }


    public void dejarUsarGPS(){
        locManager.removeUpdates(this);
    }

    public void usarGPS(){
        dejarUsarGPS();
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, 0, this);
    }
    public Location getLocation(){
        return loc;
    }

    public boolean finalizar(){
        dejarUsarGPS();
        return log.generarArchivoLog();
    }

    @Override
    public void onLocationChanged(Location location) {
        loc = location;
        latitud = location.getLatitude();
        longitud = location.getLongitude();
        velocidad = location.getSpeed();

        fechaPosicionObtenida = dateFormater.format(location.getTime());
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("tag", "ACTUALIZAR"));
        nameValuePairs.add(new BasicNameValuePair("hash_session", hash_session));
        nameValuePairs.add(new BasicNameValuePair("id_recorrido_realizado", id_recorrido_realizado));
        nameValuePairs.add(new BasicNameValuePair("latitud", String.valueOf(latitud)));
        nameValuePairs.add(new BasicNameValuePair("longitud", String.valueOf(longitud)));
        nameValuePairs.add(new BasicNameValuePair("velocidad", String.valueOf(velocidad)));
        nameValuePairs.add(new BasicNameValuePair("fecha_solicitar_posicion", fechaPedirPosicion));
        nameValuePairs.add(new BasicNameValuePair("fecha_posicion_obtenida", fechaPosicionObtenida));
        final RequestPost requestPost = new RequestPost(nameValuePairs, mContext);
        try {
            Date f = dateFormater.parse(fechaPosicionObtenida);
            f.setTime( f.getTime() + MIN_TIME);
            fechaPedirPosicion = dateFormater.format(f);
        } catch (ParseException e) {
            fechaPedirPosicion = fechaPosicionObtenida;
        }
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                try{
                    //String resultado= requestPost.execute(MOBILE_APP_URL+"actualizar_posicion").get();
                    String resultado= requestPost.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, MOBILE_APP_URL+"actualizar_posicion").get();
                    Log.i("Resultado", id_recorrido_realizado+resultado);
                    if (!resultado.equals("NoInternet")) {
                        JSONObject returnArray = new JSONObject(resultado);
                        //if(informacionJSON.getString("actualizacion").equals("1")){
                        if (!returnArray.getBoolean("error")) {
                            if (returnArray.getBoolean("finalizar_recorrido")) {
                                final MediaPlayer mp = MediaPlayer.create(mContext, R.raw.recorrido_finalizado_correctamente);
                                try {
                                    mp.start();
                                    dejarUsarGPS();
                                    MySQLiteHelperRecorrido dbHelper = new MySQLiteHelperRecorrido(activity);
                                    dbHelper.eliminarRecorrido(1);
                                    activity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            activity.finish();
                                        }
                                    });
                                } catch (Exception e) {
                                }
                            }
                            if (!returnArray.isNull("parada_cercana") && returnArray.getString("llego_parada").equals("no")) {
                                try {
                                    int id_parada_cercana = returnArray.getInt("parada_cercana");
                                    if (!ids_paradas_cercanas.contains(id_parada_cercana)) {
                                        ids_paradas_cercanas.add(id_parada_cercana);
                                        final MediaPlayer mp = MediaPlayer.create(mContext, R.raw.se_acerca_parada);
                                        try {
                                            mp.start();
                                        } catch (Exception e) {
                                        }
                                    }
                                } catch (NumberFormatException e) {
                                    try {
                                        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                                        r.play();
                                    } catch (Exception ex) {
                                    }
                                }
                            }
                            if (returnArray.getString("llego_parada").equals("si")) {
                                int id_parada_cercana = returnArray.getInt("parada_cercana");
                                if (!ids_paradas_cercanas.contains(id_parada_cercana))
                                    ids_paradas_cercanas.add(id_parada_cercana);
                                final MediaPlayer mp = MediaPlayer.create(mContext, R.raw.llego_parada);
                                try {
                                    mp.start();
                                } catch (Exception e) {
                                }
                            }
                            //if (returnArray.getString("proxima_parada") != null && returnArray.getString("proxima_parada_reservas") != null) {
                            try {
                                final String pp = returnArray.getString("proxima_parada");
                                final String pp1 = returnArray.getString("proxima_parada1");
                                final String pp2 = returnArray.getString("proxima_parada2");
                                final String ppr = returnArray.getString("proxima_parada_reservas");
                                final String pd = returnArray.getString("puestos_disponibles");
                                final String po = returnArray.getString("puestos_ocupados");

                                if(pp != "null") {
                                    tvProximaParada.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvProximaParada.setText(pp);
                                        }
                                    });
                                }else{
                                    tvProximaParada.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvProximaParada.setText("");
                                        }
                                    });
                                }
                                if(ppr != "null") {
                                    tvProximaParadaReservas.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvProximaParadaReservas.setText(ppr);
                                        }
                                    });
                                }else{
                                    tvProximaParadaReservas.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvProximaParadaReservas.setText("0");
                                        }
                                    });
                                }
                                if (pp1 != "null") {
                                    tvProximaParada1.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvProximaParada1.setText(pp1);
                                        }
                                    });
                                }else{
                                    tvProximaParada1.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvProximaParada1.setText("");
                                        }
                                    });
                                }
                                if (pp2 != "null") {
                                    tvProximaParada2.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvProximaParada2.setText(pp2);
                                        }
                                    });
                                }else{
                                    tvProximaParada2.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvProximaParada2.setText("");
                                        }
                                    });
                                }
                                if (pd != "null") {
                                    tvPuestosDisponibles.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvPuestosDisponibles.setText(pd);
                                        }
                                    });
                                }else{
                                    tvPuestosDisponibles.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvPuestosDisponibles.setText("0");
                                        }
                                    });
                                }
                                if (po != "null") {
                                    tvOcupados.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvOcupados.setText(po);
                                        }
                                    });
                                }else{
                                    tvOcupados.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvOcupados.setText("0");
                                        }
                                    });
                                }

                            } catch (Exception e) {
                            }
                            //}
                            if(returnArray.getString("errorHistorial") != null && returnArray.getString("errorHistorial") != "" && returnArray.getString("errorHistorial") != "null"){
                                log.agregarLog("Error creando recorrido_realizado_historico");
                            }
                        } else {
                            if (returnArray.getBoolean("error") && returnArray.has("errorDesc")&& returnArray.getString("errorDesc")!= null && returnArray.getString("errorDesc")!= "" && returnArray.getString("errorDesc")!= "null") {
                                log.agregarLog("Hubo un error acutalizando la posicion en el metodo actualizar_posicion");
                                try {
                                    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                                    r.play();
                                } catch (Exception ex) {
                                }
                            } else if (returnArray.getBoolean("error") && returnArray.has("errorDesc2")) {
                                log.agregarLog("Hubo un error actalizando las paradas en el metodo _actualizar_rrparadas del servidor");
                            }
                        }
                    }else{
                        Log.i("Resultado","NoIntenet");
                    }
                }catch (Exception e){
                    log.agregarLog(e.toString());
                    try {
                        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                        r.play();
                    } catch (Exception ex) {}
                }
                return;
            }
        });

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
